(function(angular) {
	"use strict";
	angular.module("fs.waf").controller("cls.loan.updateController", updateController);
	updateController.$inject = [ "$scope", "$q", "$timeout", "modalService", "gridService", "layoutConfig", "validatorConfig", "authService", "arithService", "dateService", "loanService",
		 "loanInterestService", "loanPastdueService" ];
	function updateController($scope, $q, $timeout, modalService, gridService, layoutConfig, validatorConfig, authService, arithService, dateService, loanService, 
			loanInterestService, loanPastdueService) {
		var ctrl = this, params = $scope.$stateParams.params;
		ctrl.validatorConfig = validatorConfig;
		ctrl.spreadTierInnerGridOptions = {};
		ctrl.loanIntSpreadTier2Column = {};
		ctrl.loanIntRateTypeOptions = [];
		ctrl.interestGeneral1Config = [];
		ctrl.interestGeneral2Config = [];
		ctrl.interestGeneral3Config = [];
		/** ***************Past Due****************** */
		if (ctrl.validatorConfig) {
			layoutConfig.formConfigs.pastdueSchd.tableConfigs.table.validatorConfig = ctrl.validatorConfig.loanPsd.pastdueSchdList;
			layoutConfig.formConfigs.pastdueCustTier.tableConfigs.table.validatorConfig = ctrl.validatorConfig.loanPsd.tierBaseRateCusts;
			layoutConfig.formConfigs.pastdueMixTier.tableConfigs.table.validatorConfig = ctrl.validatorConfig.loanPsd.tierBaseRateMixs;
		}
		ctrl.pastdueInnerGridOptions = gridService.createInnerGridOptions($scope, layoutConfig.formConfigs.pastdueSchd.tableConfigs.table, function(eventRow, selectedRows) {
			ctrl.selectedPastdues = selectedRows;
		});
		ctrl.pastdueInnerGridOptions.data = "vm.loan.loanPsd.pastdueSchdList";

		ctrl.custTierInnerGridOptions = gridService.createInnerGridOptions($scope, layoutConfig.formConfigs.pastdueCustTier.tableConfigs.table, function(eventRow, selectedRows) {
			ctrl.pastDueSelectedCustTiers = selectedRows;
		});
		ctrl.custTierInnerGridOptions.data = "vm.loan.loanPsd.tierBaseRateCusts";

		ctrl.mixTierInnerGridOptions = gridService.createInnerGridOptions($scope, layoutConfig.formConfigs.pastdueMixTier.tableConfigs.table, null);
		ctrl.mixTierInnerGridOptions.data = "vm.loan.loanPsd.tierBaseRateMixs";
		/** ***************Past Due****************** */

		ctrl.init = function() {
			loanService.getLoanUpdateOptions().then(function(initData) {
				return $q(function(resolved, rejected) {
					var loan = {};
					angular.merge(loan, initData);
					// init interest tab name, intcat value: res key, intca
					// label: res msg
					ctrl.intCatLabel = loanInterestService.initIntCatLabel(loan.intCatOptions);
					resolved(loan);
				});
			}).then(function(loan) {
				return $q(function(resolved, rejected) {
					authService.updateInit(params).then(function(response) {
						loan = angular.merge(loan, response.data.model);
						loan.taskId = response.data.task.taskId;
						resolved(loan);
					});
				});
			}).then(function(loan) {
				return $q(function(resolved, rejected) {
					loanService.getLoanUpdateProdCodeOptionData(loan.loanInfo.prodSubtype).then(function(prodCodeJson) {
						ctrl.prodCodeOptions = prodCodeJson.prodCode;
						resolved(loan);
					});
				});
			}).then(function(loan) {
				// convert loanInts list to loanIntObject object
				loanInterestService.initLoanIntObject(loan);
				loanInterestService.setLoanInfoToInterest(loan);
				// init interest tab"s table(spreadTierInnerGridOptions,
				// custTierInnerGridOptions, mixTierInnerGridOptions)
				initInterestTable(loan);
				var _ctrl = loanInterestService.initTierCriteria(loan, loan.loanIntSpreadTierTypeOptionsBackUp, ctrl.spreadTierInnerGridOptions, ctrl.selectedSpreadTiers);
				angular.merge(ctrl, _ctrl);
				loanService.getLayout(loan.loanInfo.prodType, loan.loanInfo.prodSubtype, "loan", "update", false).then(function(layout) {
					ctrl.layoutConfig = layout || layoutConfig;
					ctrl.loan = loan;
					// loanInterestService.formatAllInterstCriteria(ctrl.spreadTierInnerGridOptions,ctrl.loan.loanInts);
					ctrl.loan.loanPsd.pastdueSchdList = ctrl.loan.loanPsd.pastdueSchdList || [];
					ctrl.loan.loanPsd.tierBaseRateMixs = ctrl.loan.loanPsd.tierBaseRateMixs || [];
					ctrl.loan.loanPsd.tierBaseRateCusts = ctrl.loan.loanPsd.tierBaseRateCusts || [];

					// for loanPsd base rate customer
					loanPastdueService.resetPastdueTenorFrom(ctrl.loan.loanPsd.pastdueSchdList, ctrl.selectedPastdues);
					loanPastdueService.resetPastdueCustTierTenorFrom(ctrl.loan.loanPsd.tierBaseRateCusts);
				});
			});
		};
		
		ctrl.prodCodeChanged = function(loan, formCtrl, isInitialized) {
			if (loan && loan.loanInfo && loan.loanInfo.prodCode) {
				if (loan.loanInfo.prodCodeOld != loan.loanInfo.prodCode) {
					var resetLayout = true;
					if (!loan.loanInfo.prodCodeOld) {
						resetLayout = false;
					}
					loan.loanInfo.prodCodeOld = loan.loanInfo.prodCode;
					loanService.getProdCodeChangedData({
						"prodCode" : loan.loanInfo.prodCode
					}).then(function(prodCodeChangedData) {
						return $q(function(resolved, rejected) {
							ctrl.loan.ccyOptions = prodCodeChangedData.ccyOptions;
							ctrl.loan.assetTypeOptions = prodCodeChangedData.assetTypeOptions;
							ctrl.loan.loanInfo.prodType = prodCodeChangedData.prodType;
							ctrl.loan.loanInfo.prodSubtype = prodCodeChangedData.prodSubType;
							ctrl.loan.loanInfo.product = prodCodeChangedData.product;
							ctrl.loan.prodSubType = prodCodeChangedData.voProdSubtype || {};
							ctrl.pastdueInnerGridOptions.enableOperation = ctrl.loan.prodSubType.utPastdueSchd != "N" ? true : false;
							loanService.resetIntAndPastdueTableReadonly(ctrl);
							resolved();
						});
					}).then(function() {
						if (resetLayout) {
							loanService.getLayout(ctrl.loan.loanInfo.prodType, ctrl.loan.loanInfo.prodSubtype, "loan", "update", false).then(function(layout) {
								ctrl.layoutConfig = layout || layoutConfig;
								var tmp = angular.copy(ctrl.loan);
								$timeout(function() {
									ctrl.loan = tmp;
								});
							});
						}
					});
				}
			}
		};
		
		ctrl.communityIdChanged = function(loan){
			var loanInfo = loan.loanInfo;
			if(loanInfo && loanInfo.communityId){
				loanService.getApCommunity(loanInfo.communityId).then(function(map){
					if(map && map.company){
						loanInfo.obligorCode = map.company.companyCode;
						loanInfo.obligorName = map.company.companyName;
						loanInfo.obligorAddr1 = map.company.companyAddr1;
						loanInfo.obligorAddr2 = map.company.companyAddr2;
						loanInfo.obligorAddr3 = map.company.companyAddr3;
						loanInfo.obligorAddr4 = map.company.companyAddr4;
						loanInfo.obligorCity = map.company.companyCity;
						loanInfo.obligorZip = map.company.companyZip;
						loanInfo.obligorState = map.company.companyState;
						loanInfo.obligorCountry = map.company.companyCountry;
					}
				});
			}
		};

		ctrl.save = function() {
			var messages = [];
			var msg2 = validateCustTier(ctrl);
			if (msg2)
				messages.push(msg2);
			loanService.validateBilling(ctrl.loan, messages);
			if (messages.length > 0) {
				modalService.openErrorDialogs({
					"messages" : messages
				});
			} else {
				loanService.deleteInterestLoanInfo(ctrl.loan);
				loanInterestService.processInterest(ctrl.loan);
				return authService.updateSaved(ctrl.loan).then(submitSuccessful, submitFailed);
			}
		};

		ctrl.settlement = function() {
			var messages = [];
			var msg2 = validateCustTier(ctrl);
			if (msg2)
				messages.push(msg2);

			loanService.validateBilling(ctrl.loan, messages);
			if (messages.length > 0) {
				modalService.openErrorDialogs({
					"messages" : messages
				});
			} else {
				loanService.deleteInterestLoanInfo(ctrl.loan);
				loanInterestService.processInterest(ctrl.loan);
				return authService.updateSubmitted(ctrl.loan).then(submitSuccessful, submitFailed);
			}
		};

		ctrl.cancel = function() {
			modalService.openConfirmDialogs({
				"messages" : [ {
					msg : "title.dialog.confirm.cancel",
					args : [ ctrl.loan.primaryKey ]
				} ],
				"btnCallback" : {
					"ok" : function() {
						loanService.deleteInterestLoanInfo(ctrl.loan);
						loanInterestService.processInterest(ctrl.loan);
						authService.updateCancelled(ctrl.loan).then(cancelSuccessful, cancelFailed);
					}
				}
			});
		};

		function submitSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				"messages" : [ "title.dialog.successful.submit" ],
				"btnCallback" : {
					"close" : function() {
						$scope.go("cls.workflow.wfTxn.list");
					}
				},
				"redirections" : [ {
					"name" : "title.infobar.workflow.list",
					"state" : "cls.workflow.wfTxn.list",
					"params" : {}
				} ]
			});
		}

		function submitFailed(response) {
			modalService.openErrorDialogs({
				"messages" : response.error
			});
		}

		function cancelSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				"messages" : [ "title.dialog.successful.cancel" ],
				"btnCallback" : {
					"close" : function() {
						$scope.go("cls.workflow.wfTxn.list");
					}
				},
				"redirections" : [ {
					"name" : "title.infobar.workflow.list",
					"state" : "cls.workflow.wfTxn.list",
					"params" : {}
				} ]
			});
		}

		function cancelFailed(response) {
			modalService.openErrorDialogs({
				"messages" : response.error
			});
		}

		ctrl.loanIntSpreadTierType2Changed = function(param, form, firstLoad) {
			ctrl.loanIntSpreadTierTypeOptions = loanInterestService.loanIntSpreadTierType2Changed(ctrl.loan, param, firstLoad, ctrl.spreadTierInnerGridOptions, ctrl.loanIntSpreadTier2Column);
		};

		ctrl.spreadTierValueChanged = function(param, form, firstLoad) {
			if (!firstLoad) {
				loanInterestService.loanIntRateChanged(ctrl.loan, param._intCat);
			}
		};

		ctrl.criteriaChanged = function(currTierCriteria, form, flag) {
			if (!flag) {
				loanInterestService.resetSpreadTierValue(ctrl.loan, currTierCriteria);
				loanInterestService.loanIntRateChanged(ctrl.loan, currTierCriteria._intCat);
			}
		};

		ctrl.loanIntCalcMethodChanged = function(itemInterest) {
			if (!itemInterest || !itemInterest.intCat)
				return;
			ctrl.loanIntRateTypeOptions[itemInterest.intCat] = loanInterestService.loanIntCalcMethodChanged(ctrl.loan, itemInterest);
		};

		ctrl.intRateSpread_defaultChanged = function(itemInterest, form, isFirst) {
			if (isFirst) {
				return;
			}
			loanInterestService.intRateSpread_defaultChanged(ctrl.loan, itemInterest);
		};
		
		function getIntRateSpread(itemInterest){
			if(itemInterest.intRateType == "A"){
				itemInterest.intRateSpread_a = itemInterest.intRateSpread;
			}else if(itemInterest.intRateType == "P"){
				itemInterest.intRateSpread_p = itemInterest.intRateSpread;
			}else{
				itemInterest.intRateSpread_default = itemInterest.intRateSpread;
			}
		};

		ctrl.loanIntRateTypeChangedFunctions = function(itemInterest, form, firstLoad) {
			if (firstLoad) {
				return;
			}
//			itemInterest.intRateSpread = 0;
		};

		ctrl.loanIntSpreadTierTypeChangedFunctions = function(itemInterest, form, firstLoad) {
			ctrl.loanIntSpreadTierType2Options = loanInterestService.loanIntSpreadTierTypeChangedFunctions(ctrl.loan, itemInterest, firstLoad, ctrl.spreadTierInnerGridOptions);
		};

		ctrl.interestIndexRefChanged = function(itemInterest, form, fisrtLoad) {
			loanInterestService.updateInterestToLoanInfo(ctrl.loan, itemInterest);
		};
		
		ctrl.initItemInterest = function(itemInterest){
			if(itemInterest){
				var layout = angular.copy(ctrl.layoutConfig.formConfigs.interestGeneral1);
				layout.gridConfigs.intRateType.options.data = "vm.loanIntRateTypeOptions['" + itemInterest.intCat + "']";
				ctrl.interestGeneral1Config[itemInterest.intCat] = layout;
				ctrl.interestGeneral2Config[itemInterest.intCat] = angular.copy(ctrl.layoutConfig.formConfigs.interestGeneral2);
				ctrl.interestGeneral3Config[itemInterest.intCat] = angular.copy(ctrl.layoutConfig.formConfigs.interestGeneral3);
				getIntRateSpread(itemInterest);
			}
		};

		/** ******************** Interest ************************** */

		/** ***********Past Due**************** */
		ctrl.custTierMoreDataDyna = function(obj) {
			loanPastdueService.custTierMoreDataDyna(obj);
		};

		ctrl.addPastdue = function(row) {
			loanPastdueService.addPastdue(row, ctrl.loan.loanPsd.pastdueSchdList);
		};

		ctrl.removePastdue = function(row) {
			loanPastdueService.resetPastdueTenorFrom(ctrl.loan.loanPsd.pastdueSchdList, ctrl.selectedPastdues);
		};

		ctrl.loanPsdPastdueTenorChanged = function(rowObj, form, firstLoad) {
			if (firstLoad) {
				return;
			}
			loanPastdueService.pastdueTenorChanged(ctrl.loan.loanPsd.pastdueSchdList, rowObj);
		};

		ctrl.loanPsdPastdueGraceChanged = function(value, form, firstLoad) {
			if (firstLoad) {
				return;
			}
			loanPastdueService.pastdueGraceChanged(ctrl.loan.loanPsd.pastdueSchdList, value);
		};

		ctrl.pastDueIntBaseTypeChanged = function() {
			loanPastdueService.pastDueIntBaseTypeChanged(ctrl.loan);
		};

		ctrl.addPastdueCustTier = function(row) {
			loanPastdueService.addPastdueCustTier(row, ctrl.loan.loanPsd.tierBaseRateCusts);
		};

		ctrl.removePastdueCustTier = function() {
			loanPastdueService.resetPastdueCustTierTenorFrom(ctrl.loan.loanPsd.tierBaseRateCusts, ctrl.pastDueSelectedCustTiers);
		};

		function validateCustTier() {
			loanPastdueService.validateCustTier(ctrl.loan);
		}

		ctrl.pastdueCustTierTenorChanged = function(objModel, form, fisrtLoad) {
			if (fisrtLoad)
				return;
			loanPastdueService.resetPastdueCustTierTenorFrom(ctrl.loan.loanPsd.tierBaseRateCusts);
		};
		/** ***********Past Due**************** */

		/** *************general begin***************** */
		ctrl.loanInfoIndexRefChanged = function(obj, form, fisrtLoad) {
			if (!fisrtLoad) {
				loanInterestService.setLoanInfoToInterest(ctrl.loan);
			}
		};

		ctrl.loanCcyChanged = function() {
			if (ctrl.loan.loanInfo.loanCcy) {
				loanPastdueService.resetIntRateIndexOptions(ctrl.loan);
			}
			loanInterestService.setLoanInfoToInterest(ctrl.loan);
		};

		ctrl.generalMaturityDateChanged = function(value) {
			loanService.generalMaturityDateChanged(ctrl.loan);
		};
		ctrl.generalTenorDaysChanged = function() {
			loanService.generalTenorDaysChanged(ctrl.loan);
		};
		/** *************general end***************** */

		/** ************* Billing Schedule begin***************** */
		ctrl.billOnEomFlagChanged = function(loan, form, firstLoad) {
			if (!firstLoad && ctrl.loan.loanBill.billFirstOn && (dateService.compareDate(ctrl.loan.loanBill.billFirstOn, ctrl.loan.loanBill.billFirstOnTmp) != 0)) {
				if ("M" == ctrl.loan.loanBill.billFreqType || "Q" == ctrl.loan.loanBill.billFreqType) {
					if (ctrl.loan.loanBill.billOnEomFlag == "Y") {
						loanService.setBillFirstOnNew(ctrl.loan);
					}
				}
			}
		};
		ctrl.billFirstOnChanged = function(loan, form, firstLoad) {
			if (!firstLoad && ctrl.loan.loanBill.billFirstOn && (dateService.compareDate(ctrl.loan.loanBill.billFirstOn, ctrl.loan.loanBill.billFirstOnTmp) != 0)) {
				if ("M" == ctrl.loan.loanBill.billFreqType || "Q" == ctrl.loan.loanBill.billFreqType) {
					if (ctrl.loan.loanBill.billOnEomFlag == "Y") {
						loanService.setBillFirstOnNew(ctrl.loan);
					}
				}
			}
		};
		ctrl.billFreqTypeChanged = function(loan, form, firstLoad) {
			if (!firstLoad && ctrl.loan.loanBill.billFirstOn && (dateService.compareDate(ctrl.loan.loanBill.billFirstOn, ctrl.loan.loanBill.billFirstOnTmp) != 0)) {
				if ("M" == ctrl.loan.loanBill.billFreqType || "Q" == ctrl.loan.loanBill.billFreqType) {
					if (ctrl.loan.loanBill.billOnEomFlag == "Y") {
						loanService.setBillFirstOnNew(ctrl.loan);
					}
				}
			}
		};

		ctrl.billIntFlagChanged = function() {
			if (ctrl.loan.loanBill && ctrl.loan.loanBill.billIntFlag != "Y") {
				ctrl.loan.loanBill.billIntWithPrinc = "N";
			}
		};

		/** ************* Billing Schedule end***************** */

		// init interest tab"s table
		function initInterestTable(loan) {
			if (loan.loanInts) {
				angular.forEach(loan.loanInts, function(loanInt) {
					var intCat = loanInt.intCat;
					// init spreadTierList
					ctrl.spreadTierInnerGridOptions[intCat] = gridService.createInnerGridOptions($scope, angular.copy(layoutConfig.formConfigs.interestSpreadTier.tableConfigs.table), function(
							eventRow, selectedRows) {
						ctrl.selectedSpreadTiers[intCat] = selectedRows;
					});
					ctrl.spreadTierInnerGridOptions[intCat].data = loanInt.spreadTierList;
					// init tierCriterias
					ctrl.custTierInnerGridOptions[intCat] = gridService.createInnerGridOptions($scope, angular.copy(layoutConfig.formConfigs.custTier.tableConfigs.table));
					ctrl.custTierInnerGridOptions[intCat].data = loanInt.tierBaseRateCusts;
					// init tierCriterias
					ctrl.mixTierInnerGridOptions[intCat] = gridService.createInnerGridOptions($scope, angular.copy(layoutConfig.formConfigs.mixTier.tableConfigs.table));
					ctrl.mixTierInnerGridOptions[intCat].data = loanInt.tierBaseRateMixs;
				});
			}
		}
	}
})(angular);
